package com.zjff.mobiletwo.controller;

import com.taobao.api.internal.util.StringUtils;
import com.zjff.mobiletwo.dao.UserDao;
import com.zjff.mobiletwo.entity.ResultEntity;
import com.zjff.mobiletwo.entity.UserEntity;
import com.zjff.mobiletwo.service.*;
import com.zjff.mobiletwo.service.util.CreateJwt;
import com.zjff.mobiletwo.service.util.PraseJwtTest;
import com.zjff.mobiletwo.service.util.RedisUtils;
import com.zjff.mobiletwo.service.util.TextUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin//跨域
@RestController//遵循RestFul
@RequestMapping("v2/User/")
public class UserController extends BaseController {
    @Resource
    UserService userService;
    @Resource
    UserDao userDao;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    UpdateServiceImpl updateService;
    @Resource
    TextService textService;
    @Resource
    TokenService tokenService;
    @Resource
    FileService fileService;

    //根据id获取用户信息
    @GetMapping("getUserDetailById")
    private  String getUserDetailById(int id){
        return userService.getUserDetailById(id);
    }
    /**
     * 通过用户手机号查找用户详情
     * @param phone 手机号
     * @return
     */
    @GetMapping("getUserByPhone")
    private  String getUserByPhone( String phone){
        if (phone.equals("")){
            return ResultEntity.Fail(-10007,"请输入手机号!");
        }
        return userService.getUserByPhone(phone);
    }
    /**
     * 根据用户id修改账号
     * @param id 用户id
     * @param username 原账号
     * @param newname 新账号
     * @param conname 确认账号
     * @return
     */
    @PutMapping("updateUsername")
    private String updateUsername(@RequestParam(value = "id",defaultValue = "-1")int id,
                                  @RequestParam(value = "username")String username,
                                  @RequestParam(value = "newname")String newname,
                                  @RequestParam(value = "conname")String conname){
        if (id==-1 || username.equals("")){
            return ResultEntity.Fail(-10007,"输入为空修改失败!");
        }
        return userService.updateUsername(id, username, newname, conname);
    }
    /**
     * **修改邮箱
     * @param id 用户id
     * @param email 邮箱
     * @return JSON（String)
     */
    @PutMapping("updateEmail")
    private String updateEmail(@RequestParam(value = "id",defaultValue = "-1")int id,
                               @RequestParam(value = "email")String email){
        if (id==-1 || email.equals("")){
            return ResultEntity.Fail(-10007,"修改邮箱失败!");
        }

        return userService.updateEmail(email,id);
    }
    /**
     * **修改昵称
     * @param id 用户id
     * @param pname 昵称
     * @return JSON（String)
     */
    @PutMapping("updatePname")
    private String updatePname(@RequestParam(value = "id",defaultValue = "-1")int id,
                               @RequestParam(value = "pname")String pname){
        if (id==-1 || pname.equals("")){
            return ResultEntity.Fail(-10007,"修改昵称失败!");
        }
        return userService.updatePname(pname,id);
    }
    /**
     * **修改手机号
     * @param id 用户id
     * @param phone 手机号
     * @return JSON（String)
     */
    @PutMapping("updatePhone")
    private String updatePhone(@RequestParam(value = "id",defaultValue = "-1")int id,
                               @RequestParam(value = "phone")String phone){
        if (id==-1 || phone.equals("")){
            return ResultEntity.Fail(-10007,"修改手机号失败!");
        }
        return userService.updatePhone(phone,id);
    }
    /**
     * 添加密码用于手机短信注册无登录密码的情况
     * @param password 密码
     * @param id 用户id
     * @return
     */
    @PutMapping ("addPassword")
    private String addPassword(@RequestParam(value = "id",defaultValue = "-1")int id,
                               @RequestParam(value = "password")String password){
        if (id==-1 || password.equals("")){
            return ResultEntity.Fail(-10007,"失败!");
        }
        return userService.addPassword(password,id);
    }
    /**
     * 添加账号用于手机短信注册无账号的情况
     * @param username 账号(用户名)
     * @param id 用户id
     * @return
     */
    @PutMapping ("addUsername")
    private String addUsername(@RequestParam(value = "id",defaultValue = "-1")int id,
                               @RequestParam(value = "username")String username){
        if (id==-1 || username.equals("")){
            return ResultEntity.Fail(-10007,"失败!");
        }
        return userService.addUsername(username,id);
    }
    /**
     * 修改密码
     * @param username 用户名
     * @param password 旧密码
     * @param newPsw 新密码
     * @param conPaw 确认密码
     * @return
     */
    @PutMapping("updatepass")
    public String updatePassword(@RequestParam(value = "username") String username,
                                 @RequestParam(value = "password") String password,
                                 @RequestParam(value = "newPsw") String newPsw,
                                 @RequestParam(value = "conPaw") String conPaw){
        UserEntity user = userDao.getUserByUsername(username);
        if(user != null){
            if(!user.getPassword().equals(password)){
                System.out.println("原密码错误");
                return ResultEntity.Fail(-10007,"原密码错误!");
            } else if (user.getPassword().equals(newPsw)) {
                System.out.println("新密码不能与旧密码相同！");
                return ResultEntity.Fail(-10007,"新密码不能与旧密码相同!");
            } else if(!newPsw.equals(conPaw)){
                System.out.println("两次密码输入不同！");
                return ResultEntity.Fail(-10007,"两次密码输入不同!");
            }else {
                return ResultEntity.Success(null,userDao.updatePasswordByUsername(username,newPsw),0,"修改密码成功!");
            }
        }else {
            System.out.println("不存在此用户");
            return ResultEntity.Fail(-10007,"不存在此用户!");
        }

    }
    /**
     * 重置密码
     * @param username 用户名
     * @param password 密码
     * @param conPaw 确认密码
     * @return
     */
    @PutMapping("resetpass")
    public String resetPassword(@RequestParam(value = "username") String username,
                                 @RequestParam(value = "password") String password,
                                 @RequestParam(value = "conPaw") String conPaw){
        UserEntity user = userDao.getUserByUsername(username);
        if (user !=null){
            if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)||StringUtils.isEmpty(conPaw)){
                System.out.println("输入不能为空");
                return ResultEntity.Fail(-10007,"输入不能为空!");
            } else if (!password.equals(conPaw)) {
                System.out.println("两次密码输入不同！");
                return ResultEntity.Fail(-10007,"两次密码输入不同!");
            }else {
                return ResultEntity.Success(null,userDao.updatePasswordByUsername(username,password),0,"修改密码成功!");
            }
        }else {
            System.out.println("不存在此用户");
            return ResultEntity.Fail(-10007,"不存在此用户!");
        }

    }
    /**
     * **根据id删除用户详情
     * @param username 用户名
     * @return JSON（String)
     */
    @DeleteMapping("deluser")
    private String deluser(@RequestParam(value = "username")String username){
        if (username.equals("")){
            return ResultEntity.Fail(-10007,"删除用户失败!");
        }
        return userService.deluser(username);
    }
    /**
     * 通过用户手机号获取验证码
     * @param phone 手机号
     * @return
     */
    @GetMapping("getauthcode")
    private String authcode_get(@RequestParam(value = "phone", required = false)String phone){
        UserEntity user = userDao.getUserByPhone(phone);
        if (StringUtils.isEmpty(phone)){
            return ResultEntity.Fail(-10007,"输入不能为空!");
        }else if (user ==null){
            return ResultEntity.Fail(-10007,"手机号未注册!");
        } else {
            return ResultEntity.Success(null,userService.authcode_get(phone),0,"发送验证码成功!");
        }
    }
    /**
     * 验证码校验
     * @param phone    手机号
     * @param authcode 验证码
     * @return
     */
    @PostMapping("ifauthcode")
    private String authcode(@RequestParam(value = "phone", required = false)String phone,
                            @RequestParam(value = "authcode", required = false)String authcode){
        if (phone.equals("") || authcode.equals("")){
            return ResultEntity.Fail(-10007,"输入为空!");
        }
        return ResultEntity.Success(null,phone,0,"校验成功");
    }
    /**
     * 验证码登录
     * @param phone    手机号
     * @param authcode 验证码
     * @return
     */
    @PostMapping("loginauthcode")
    private Object authcode_login(@RequestParam(value = "phone", required = false)String phone,
                                  @RequestParam(value = "authcode", required = false)String authcode,
                                  HttpServletRequest request){
        UserEntity user = userDao.getUserByPhone(phone);
        Map<String,Object> map=new HashMap<>();
        if (StringUtils.isEmpty(phone)){
            return ResultEntity.Fail(-10007,"输入不能为空!");
        }else if (user == null){
            return ResultEntity.Fail(-10007,"手机号未注册!");
        }else if (!redisUtils.get(phone).equals(authcode)){
            return ResultEntity.Fail(-10007,"验证码错误!");
        }else {
            request.getSession().setAttribute("session_user",user);//登录成功后将用户放入session中，用于拦截
            String token = tokenService.getToken(user);
            map.put("code",0);
            map.put("msg","登入成功");
            map.put("token",token);
            map.put("data",userService.authcode_login(phone,authcode));

        }
        return map;
    }
    /**
     * 注册用户详情
     * @param username 用户名
     * @param password 密码
     * @param email 邮箱
     * @param phone 手机号
     * @param pname 昵称
     * @param gender 性别
     * @return
     */
    @PostMapping("addUser")
    private String addUser(@RequestParam(value = "username",defaultValue = "")String username,
                           @RequestParam(value = "password",defaultValue = "")String password,
                           @RequestParam(value = "email",defaultValue = "")String email,
                           @RequestParam(value = "phone",defaultValue = "")String phone,
                           @RequestParam(value = "pname",defaultValue = "")String pname,
                           @RequestParam(value = "gender",defaultValue = "-1")int gender
    ){
        UserEntity user = userDao.getUserByUsername(username);
        UserEntity userr = userDao.getUserByPhone(phone);
        if (StringUtils.isEmpty(username)) {
            return ResultEntity.Fail(-10007,"用户名为空!");
        }else if(user !=null){
            return ResultEntity.Fail(-10007,"用户名重复!");
        } else if (StringUtils.isEmpty(pname)) {
            return ResultEntity.Fail(-10007,"昵称为空!");
        } else if (StringUtils.isEmpty(password)) {
            return ResultEntity.Fail(-10007,"密码为空!");
        } else if (StringUtils.isEmpty(email)) {
            return ResultEntity.Fail(-10007,"电子邮箱为空!");
        } else if(StringUtils.isEmpty(phone)){
            return ResultEntity.Fail(-10007,"手机号为空!");
        }else if (userr !=null) {
            return ResultEntity.Fail(-10007,"手机号重复!");
        }else {
            return userService.addUser(username,password,email,phone,pname,gender);
        }
    }
    /**
     * 通过手机号获取验证码
     * @param phone 手机号
     * @return
     */
    @GetMapping("authcode")
    private String authcode(@RequestParam(value = "phone",defaultValue = "-1")String phone){
        if (phone.equals("")){
            return ResultEntity.Fail(-10007,"获取验证码失败!");
        }
        return userService.authcode(phone);
    }
    /**
     * 验证码注册
     * @param phone    手机号
     * @param authcode 验证码
     * @return
     */
    @PostMapping("addUserByPhone")
    private String addUserByPhone(@RequestParam(value = "phone",defaultValue = "")String phone,
                                  @Param(value = "authcode") String authcode){
        if (phone.equals("") || authcode.equals("")){
            return ResultEntity.Fail(-10007,"输入不能为空!");
        }
        return userService.addUserByPhone(phone,authcode);
    }
    /**
     * 登录操作
     * @param username 用户名
     * @param password 用户密码
     * @return
     */
    @PostMapping(value = "login")
    public Object login(@RequestParam(value = "username", required = false)String username,
                        @RequestParam(value = "password", required = false)String password,
                        HttpServletRequest request, HttpSession session){
        Map<String,Object> map=new HashMap<>();
        if (TextUtils.Isempty(username) ||TextUtils.Isempty(password)){
            map.put("code",100);
            map.put("msg","参数不能为空");
        }else {
            UserEntity user= textService.login(username);
            if(user!=null){
                if (password.equals(user.getPassword())){
                    request.getSession().setAttribute("session_user",user);//登录成功后将用户放入session中，用于拦截
                    session.setAttribute("id",user.getId());
                    session.setAttribute("username",user.getUsername());
                    System.out.println(getuidFromSession(session));
                    System.out.println(getUsernameFromSession(session));
                    String token = tokenService.getToken(user);
                    map.put("code",0);
                    map.put("msg","登入成功");
                    map.put("token",token);
                    map.put("user",user);
                }else {
                    map.put("code",101);
                    map.put("msg","用户名或者密码错误");
                }
            }else {
                map.put("code",102);
                map.put("msg","不存在该用户");
            }
        }
        return map;
    }

    @RequestMapping(value = "tokenSign")
    public Object tokenSign(@RequestParam(value = "token")String token){
        Map<String,Object>map=new HashMap<>();
        if(TextUtils.Isempty(token)){
            map.put("code",100);
            map.put("msg","参数不能为空");
        }else{
            try{
                Claims claims= PraseJwtTest.tokenToOut(token);
                Integer id=Integer.valueOf(claims.getId());
                String name=claims.getSubject();
                UserEntity user=textService.getuserById(id);
                if(name!=null&&claims.getId()!=null&&name.equals(user.getUsername())){
                    String newtoken= CreateJwt.getoken(user);
                    map.put("token",newtoken);
                    map.put("user",user);
                    map.put("code",0);
                    map.put("msg","登入成功");
                }else {
                    map.put("code",101);
                    map.put("msg","token错误");
                }
            }catch (Exception e){
                map.put("code",102);
                map.put("msg","token格式不正确");
            }
        }
        return map;
    }



    //注册操作
    @RequestMapping("register")
    public String register(UserEntity user){
        return userService.register(user);
    }



    //退出登录
    @RequestMapping("outUser")
    public void outUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute("session_user");
        response.sendRedirect("/user/toIndex");
    }
    /**
     * 更新用户头像
     * @param file 用户头像文件
     * @param userId 用户id
     * @return
     */
    @PostMapping("upfile")
    private String upfile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("userId") int userId
    ){
        try{
            String filePath=fileService.AddFileToKoDo(fileService.AddFileToLocal(file));//将本地文件上传到七牛云并返回七牛云上的URL
            if (userService.upLoadHeadImg(filePath,userId)>0){
                return ResultEntity.Success(null,filePath,0,"更新成功!");//将七牛云的URL更新到用户表中
            }else {
                return ResultEntity.Fail(-10007,"更新失败!");
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultEntity.Fail(-10007,"上传失败!");
        }

    }


}
